import { createWebHistory, createRouter } from 'vue-router'
import { GetToken } from '@/utils/auth';

const routes = []

const modules = import.meta.glob('@/view/**/*/route.config.js', { eager: true });
for (const key in modules) {
    if (Array.isArray(modules[key].default)) {
        modules[key].default.forEach(item => {
            routes.push(item);
        })
    }
}


const router = createRouter({
    history: createWebHistory(),
    routes,
})

router.beforeEach((to, from, next) => {
    if (to.meta.title) {
        document.title = to.meta.title;
    } else {
        document.title = import.meta.env.VITE_TITLE;
    }
    const token = GetToken();
    if (to.meta.auth === false) {
        next();
    } else if (token) {
        next();
    } else {
        next('/login');
    }
});

const addRouters = function (routers) {
    for (let i = 0; i < routers.length; i++) {
        const element = routers[i];
        router.addRoute(element);
    }
}

export { router, addRouters }